package com.whstudio.util.mvc.data.sql;

import java.util.Iterator;

import com.whstudio.util.string.StrUtil;

public class QuerySql extends ASql{
	private String orderBy=null;
	public ISql setEnds(String orderBy) {
		this.orderBy = orderBy;
		return this;
	}
	public ISql build(){
		StringBuilder builder=new StringBuilder();
		
		builder.append(SQL_SELECT).append(SQL_BLANK);
		for(Iterator<String> iterator=this.columns.iterator();iterator.hasNext();){
			builder.append(iterator.next()).append(SQL_COMMA);
		}
		
		builder.setCharAt(builder.length()-1, SQL_BLANK);
		builder.append(SQL_FROM).append(SQL_BLANK);
		if(tables.size()==0){
			builder.append("(").append(subSql).append(") as t");
		}else{
			for(Iterator<String> iterator=this.tables.iterator();iterator.hasNext();){
				builder.append(iterator.next()).append(SQL_COMMA);
			}
			builder.setCharAt(builder.length()-1, SQL_BLANK);
		}
		
		if(this.args.size()>0){
			builder.append(SQL_WHERE).append(SQL_BLANK);
			for(Iterator<Arg> iterator=this.args.iterator();iterator.hasNext();){
				Arg arg=iterator.next();
				if(arg.getSubSql()==null&&StrUtil.noe(arg.getValue())&&!arg.isNoValue()){
					continue;
				}
				String condition=arg.getCondition();
				if(condition==null){
					condition=""+SQL_EQUAL;
				}else if(condition.equals("")){
					condition="";
				}
				String sArg="";
				if(arg.getSubSql()==null){
					if(arg.getValue()!=null&&!arg.isNoValue()){
						sArg="'"+arg.getValue()+"'";
					}
				}else{
					sArg="("+arg.getSubSql()+")";
				}
				builder
				.append(SQL_BLANK)
				.append(arg.getColumn())
				.append(SQL_BLANK)
				.append(condition)
				.append(SQL_BLANK)
				.append(sArg)
				.append(SQL_BLANK)
				.append(SQL_AND);
			}
			int index=builder.lastIndexOf(SQL_AND);
			if(index>-1){
				builder.setLength(index);
			}
			if(builder.toString().trim().endsWith(SQL_WHERE)){
				builder.setLength(builder.lastIndexOf(SQL_WHERE));
			}
		}
		
		if(orderBy!=null){
			builder.append(SQL_BLANK).append("ORDER BY ").append(orderBy);
		}
		
		this.sql=builder.toString();
		return this;
	}
	
}
